<template>
  <div>
    <el-upload
      :class="{hidden:fileList.length>0}"
      action="#"
      list-type="picture-card"
      :file-list="fileList"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-change="change"
      :before-upload="beforeUpload"
      :http-request="upload"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-progress v-if="!percentage==0" :percentage="percentage" :color="customColorMethod" />
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import SOC from 'cos-js-sdk-v5'
const soc = new SOC({
  SecretId: 'AKID94j7E60g6GwObXEesra2E9oCJAk36sNc',
  SecretKey: 'zh9LHwLTLwGJ5apnVw72g3A0Zsuf8MJ0'
})
export default {
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      fileList: [],
      percentage: 0
    }
  },
  methods: {
    upload(params) {
      soc.putObject({
        Bucket: 'hr66-1307420772', /* 必须 */
        Region: 'ap-nanjing', /* 存储桶所在地域，必须字段 */
        Key: params.file.name, /* 必须 */
        StorageClass: 'STANDARD',
        Body: params.file, // 上传文件对象
        onProgress: (progressData) => {
          console.log(JSON.stringify(progressData))
          this.percentage = progressData.percent * 100
        }
      }, (err, data) => {
        console.log(err || data)
        this.fileList[0].url = 'http://' + data.Location
        this.percentage = 0
      })
    },
    beforeUpload(file) {
      console.log(file)
      const whileList = ['image/jpeg']
      if (!whileList.includes(file.type)) {
        this.$message.warning('只能上传jpeg格式的图片')
        return false
      }
    },
    change(file, fileList) {
      this.fileList.push({ name: file.name, url: file.url })
    },
    handleRemove(file, fileList) {
      this.fileList = []
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    customColorMethod(percentage) {
      if (percentage < 30) {
        return 'red'
      } else if (percentage < 70) {
        return '#e6a23c'
      } else {
        return '#67c23a'
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.hidden{
    ::v-deep.el-upload--picture-card{
    display: none;
}
}
</style>
